import { createRouter, createWebHistory } from 'vue-router'
import { usePermissionStore } from '../stores/permission'
import { ElMessage } from 'element-plus'

// 导入页面组件
const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/user/Login.vue')
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../views/user/Register.vue')
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        children: [
            {
                path: 'home',
                name: 'Home',
                component: () => import('../views/Home.vue')
            },
            {
                path: 'home-placeholder',
                name: 'HomePlaceholder',
                component: () => import('../views/Home.vue'),
                meta: { isPlaceholder: true, transitionDisabled: true }
            },
            {
                // 物品管理模块
                path: 'items',
                name: 'Items',
                component: () => import('../views/items/ItemList.vue')
            },
            {
                // 物品详情页面
                path: 'items/:id',
                name: 'ItemDetails',
                component: () => import('../views/items/ItemDetailsView.vue')
            },
            {
                // 库存管理模块
                path: 'inventory',
                name: 'Inventory',
                component: () => import('../views/items/InventoryView.vue')
            },
            {
                // 数据统计模块
                path: 'statistics',
                name: 'Statistics',
                component: () => import('../views/statistics/StatisticsView.vue')
            },
            {
                path: 'notifications',
                name: 'Notifications',
                component: () => import('../views/Notifications.vue')
            },
            {
                path: 'permissions',
                name: 'Permissions',
                component: () => import('../views/Permissions.vue'),
                meta: {
                    requiresAdmin: true
                }
            },
            {
                // 系统设置模块
                path: 'settings',
                name: 'Settings',
                component: () => import('../views/settings/SettingsView.vue')
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const isAuthenticated = localStorage.getItem('token')
    if (to.name !== 'Login' && to.name !== 'Register' && !isAuthenticated) {
        next({ name: 'Login' })
    } else if (to.meta.requiresAdmin) {
        // 检查用户是否有管理权限
        const permissionStore = usePermissionStore()

        // 尝试从多个来源获取locationId
        const locationId = permissionStore.currentLocationId ||
            to.query.locationId ||
            localStorage.getItem('currentLocationId')

        // 如果没有当前位置ID，先跳转到首页
        if (!locationId) {
            ElMessage.warning('请先选择一个位置')
            next({ name: 'Home' })
            return
        }

        // 确保permissionStore中的currentLocationId已设置
        if (permissionStore.currentLocationId !== locationId) {
            permissionStore.currentLocationId = locationId
            localStorage.setItem('currentLocationId', locationId)
        }

        // 检查用户权限缓存是否已加载
        const hasPermissions = Object.keys(permissionStore.userLocationPermissions).length > 0

        // 如果权限还未加载，尝试加载
        if (!hasPermissions) {
            ElMessage.warning('正在加载权限信息，请稍候...')

            // 重定向到主页，让用户稍后再尝试
            next({ name: 'Home', query: { from: 'permissions' } })
            return
        }

        // 检查用户是否有查看用户权限界面的权限
        if (permissionStore.canViewUserPermissions(locationId)) {
            next()
        } else {
            ElMessage.error('您没有权限访问用户权限页面')
            next({ name: 'Home' })
        }
    } else {
        next()
    }
})

// 添加后置守卫，确保用户登录时间数据在页面之间切换时始终是最新的
router.afterEach((to, from) => {
    // 保存当前路由以便恢复
    localStorage.setItem('lastRoute', to.fullPath);

    // 当从其他页面切换到设置页面或从设置页面切换回来时，检查用户登录时间
    if ((to.name === 'Permissions' && from.name !== 'Permissions') ||
        (from.name === 'Permissions' && to.name !== 'Permissions')) {

        // 检查是否有缓存的用户登录时间数据
        const cachedLoginTimes = localStorage.getItem('userLoginTimes');
        if (cachedLoginTimes) {
            console.log('router: 检测到页面切换，刷新用户登录时间数据');

            // 通过window事件触发刷新
            if (typeof window !== 'undefined') {
                window.dispatchEvent(new CustomEvent('refresh-login-times'));
            }
        }
    }
})

export default router 